# coding=utf8

import sys
sys.path.append('E:\\Python\\PycharmProjects\\pythonProject\\day_task')  # 新加入的
sys.path.append('E:\\Python\\PycharmProjects')
sys.path.append('E:\\Python\\PycharmProjects\\pythonProject')
print(sys.path)
from selenium import webdriver
from common.conmon import SelectFunction
import urllib.request
import itchat
import xlrd
import datetime
import time
import os
class Login(SelectFunction):
    def __init__(self, driver):
        self.driver = driver
        # driver=webdriver.Chrome()
        url='http://itm.huaguilife.cn/index'
        driver.get(url)
        driver.maximize_window()
    def login(self,name,password,num):
        login_page=self.elements('xpath','//*[@id="app"]//div[2]/input')
        login_page[0].send_keys(name)
        login_page[1].send_keys(password)
        login_page[2].send_keys(num)
        button=self.element('xpath','//*[@id="app"]/div/div[2]/form/button').click()
        time.sleep(8)
        i=0
        while True:
            or_notelement = LG.isElementExist()
            time.sleep(5)
            print(or_notelement)
            if or_notelement ==False:
                print(or_notelement, 'denglu_Fail{}'.format(i))
                LG.refush_image()
                time.sleep(5)
            else:
                print(or_notelement, 'denglu_ok')
                break
            i += 1

    def refush_image(self):
        check_click = self.element('xpath', '//*[@id="app"]/div/div[2]/form/div[3]/div/img').click()
        time.sleep(3)
        self.element('xpath', '//*[@id="app"]/div/div[2]/form/button').click()
        time.sleep(4)
    def get_Image(self,name):
    ##截的图保存在images文件夹中
        timestrmap = time.strftime('%Y%m%d_%H_%M_%S')
        imgPath = os.path.join('./daily_picture/', '%s.png' % (name+str(timestrmap)))
        # print(imgPath)
        self.driver.save_screenshot(imgPath)
        return imgPath

    def write_dailywork(self,filename, sheetname):
        curr_days  = datetime.datetime.now().strftime('%d')  # 当前系统duo
        # print(curr_days)
        self.element('xpath','//*[@id="app"]//a/li/span[text()="日报/周报"]').click()
        time.sleep(2)
        cell='//*[@id="app"]/div/div[2]/section//table/tbody/tr/td/div/div/div/div[text()="{}"]'.format(curr_days)
        time.sleep(5)
        date=self.elements('xpath', cell)
        time.sleep(5)
        date[0].click()
        time.sleep(2)
        cont=LG.excel_dailywork(filename,sheetname)
        print(cont)
        if cont:
            for i in range(1,len(cont)+1):
                # seslect_daily='//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[1]/td[2]/div'
                seslect_daily = '//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[2]/div'.format(i)
                # print(seslect_daily)
                self.element('xpath',seslect_daily).click()
                time.sleep(2)
                self.element('xpath',"//div[@class='el-scrollbar']/div/ul/li[4]").click()#选择测试
                time.sleep(1)
                content_daily='//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[3]/div'.format(i)#定位需要点击的输入框位置
                # print(content_daily)
                self.element('xpath', content_daily).click()
                time.sleep(1)
                content_daily_input='//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[3]/div/input'.format(i)#定位输入框
                # print(content_daily_input)
                self.element('xpath', content_daily_input).send_keys(cont[i-1][3]+' '+str(cont[i-1][7])+'h'+' '+str((cont[i-1][9])*100)+'%')
                # print(cont[i-1][3]+' '+str(cont[i-1][7])+'h'+' '+str((cont[i-1][9])*100)+'%')
                num_daily='//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[5]/div'.format(i)
                self.element('xpath', num_daily).click()
                num_daily_input='//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[5]/div/div/input'.format(i)
                aa=self.element('xpath', num_daily_input)
                time.sleep(1)
                aa.send_keys(str(cont[i-1][7]))
                # print(str(cont[i-1][7]))
            daily_img=LG.get_Image('日报')#截图
            # LG.remove_img(daily_img)#删除图片
            self.element('xpath','//*[@id="app"]/div/div[2]/section/div/div[2]/div/div[2]/div/div[2]/div/form/div/div').click()
            time.sleep(2)
            makesure='//*[@id="app"]/div/div[2]/section//div/div[3]/button[1]'#点击提交按钮
            self.element('xpath',makesure).click()
            LG.logout()
        else:

            makedate = datetime.date.today()
            print('%s在日报没有查询到数据，请确认是否写了日报'%(makedate))
            makesure = '//*[@id="app"]/div/div[2]/section//div/div[3]/button[1]'  # 点击提交按钮
            self.element('xpath', makesure).click()
            LG.logout()
    def excel_dailywork(self,filename, sheetname):#读取日报并返回
        makedate = datetime.date.today()
        # print(makedate)
        wb = xlrd.open_workbook(filename)  # 打开excel
        sh = wb.sheet_by_name(sheetname)  # 定位工作表
        # nrows = sh.nrows  # 获取多少行
        # ncols = sh.ncols  # 获取多少列
        # # print(nrows,ncols)
        # 获取整行和整列的值（数组）
        rows = sh.row_values(4)  # 获取第四行内容
        cols = sh.col_values(4)  # 获取第三列内容
        date = list(filter(None, cols))  # 读取excel有空白行，去除空白行，不然时间转换会报错
        # print(date)
        # # print(len(date))

        dailyvalue = []  # 存储当天系统的日报内容
        for i in range(1, len(date)):
            new_date = xlrd.xldate_as_datetime(date[i], 0).strftime('%Y-%m-%d')  # 转换读取的日期格式
            if str(makedate) == new_date:  # 判断日期格式是否与当前时间是否一致。
                value = sh.row_values(i + 2)  # 读取行的值
                dailyvalue.append(value)
            else:
                pass
        return dailyvalue

    def excel_weekwork(self,filename, sheetname):
        wb = xlrd.open_workbook(filename)  # 打开excel
        sh = wb.sheet_by_name(sheetname)  # 定位工作表
        start_cols = sh.col_values(3)  # 获取第三列内容
        stat_date = list(filter(None, start_cols))  # 读取excel有空白行，去除空白行，不然时间转换会报错
        weekvalue = []  # 存储下周计划内容
        for i in range(1, len(stat_date)):
            value = sh.row_values(i + 1)  # 读取行的值
            weekvalue.append(value)
        return weekvalue
    def isElementExist(self):
        try:
            LG_sucess = '//*[@id="app"]/div/div[1]/div[2]/div[1]/div/ul/div[3]/a/li/span'
            self.element('xpath',LG_sucess)
            return True
        except:
            return False

    def write_weekwork(self,filename,sheetname):
        week_id='//*[@id="app"]/div/div[2]/section//label/span[text()="周报"]'
        self.element('xpath',week_id).click()
        self.element('xpath','//*[@id="tab-1"]').click()#下周计划任务
        time.sleep(2)
        start_date=self.send_key_clear('xpath', '//*[@id="pane-1"]/div[1]/div/input[1]','2021-12-06')# 下周计划任务开始日期
        time.sleep(1)
        end_date = self.send_key_clear('xpath', '//*[@id="pane-1"]/div[1]/div/input[2]','2021-12-10')# 下周计划任务结束日期
        time.sleep(1)
        self.element('xpath','//*[@id="app"]/div/div[2]/div/div[2]/div/div[1]/div').click()
        wk_cont = LG.excel_weekwork(filename, sheetname)
        if wk_cont:
            for i in range(1, len(wk_cont) + 1):
                seslect_daily = '//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[2]/div'.format(i)
                # print(seslect_daily)
                time.sleep(2)
                aa=self.elements('xpath', seslect_daily)
                time.sleep(2)
                aa[1].click()
                time.sleep(2)
                self.element('xpath', "//div[@class='el-scrollbar']/div/ul/li[4]").click()  # 选择测试
                time.sleep(1)
                content_daily = '//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[3]/div'.format(i)  # 定位需要点击的输入框位置

                bb=self.elements('xpath', content_daily)
                bb[1].click()
                time.sleep(1)
                content_daily_input = '//*[@id="app"]/div/div[2]/section//div[2]/div[1]/div[2]/table/tbody/tr[{}]/td[3]/div/input'.format(i)  # 定位输入框
                self.element('xpath', content_daily_input).send_keys(wk_cont[i - 1][2])
                cc=xlrd.xldate_as_datetime(wk_cont[i - 1][3], 0).strftime('%Y-%m-%d')
                # print(cc)
                # print(type(xlrd.xldate_as_datetime(wk_cont[i - 1][3], 0).strftime('%Y-%m-%d')))
                #实际开始日期
                start_id = '//*[@id="pane-1"]//table/tbody/tr[{}]/td[5]//div'.format(i)
                start_input=self.element('xpath', start_id)
                start_input.click()
                start= '//*[@id="pane-1"]//table/tbody/tr[{}]/td[5]//div//input'.format(i)
                self.element('xpath', start).send_keys(cc)
                # 实际结束日期
                end_id = '//*[@id="pane-1"]//table/tbody/tr[{}]/td[6]//div'.format(i)
                end_input= self.element('xpath', end_id)
                end_input.click()
                dd = xlrd.xldate_as_datetime(wk_cont[i - 1][4], 0).strftime('%Y-%m-%d')
                end = '//*[@id="pane-1"]//table/tbody/tr[{}]/td[6]//div//input'.format(i)
                self.element('xpath', end).send_keys(dd)
                time.sleep(1)
                num_daily_input = '//*[@id="pane-1"]//table/tbody/tr[{}]/td[7]//div'.format(i)
                self.element('xpath', num_daily_input).click()
                daily_input='//*[@id="pane-1"]//table/tbody/tr[{}]/td[7]//div//input'.format(i)
                self.element('xpath', daily_input).send_keys(str(wk_cont[i - 1][5]))
                time.sleep(1)
                self.element('xpath','//*[@id="app"]/div/div[2]/div/div[2]/div/div[1]/div').click()
            week_img=LG.get_Image('周报计划')#截图周报
            # LG.remove_img(week_img)#删除图片
            LG.save_sumbut_weekwork()
            LG.logout()
        else:
            print('今天是周%s，不需要填写周报，请知悉' % (datetime.datetime.now().weekday() + 1))
            LG.logout()
    def save_sumbut_weekwork(self):
        save_id='//*[@id="app"]/div/div[2]/section//button[1]/span'
        self.element('xpath',save_id).click()#保存
        time.sleep(5)
        sumut_id='//*[@id="app"]/div/div[2]/section//button[3]/span'#提交周报
        self.element('xpath', sumut_id).click()
    def logout(self):
        time.sleep(2)
        lgout_id='//*[@id="app"]//div[3]/div[2]/div//img'
        self.element('xpath', lgout_id).click()
        out_id='//ul//li//span[text()="退出登录"]'
        time.sleep(3)
        self.element('xpath', out_id).click()
        time.sleep(12)
        sure_id='/html/body/div[2]/div/div[3]/button[2]/span'
        self.element('xpath', sure_id).click()

    def remove_img(self,imgPath):#
        file_name=imgPath
        if os.path.exists(file_name):
            os.remove(file_name)
            print('成功删除文件:', file_name)
        else:
            print('未找到此文件:', file_name)
        return file_name

    # def send_itchat(self):#发送到微信上
    #     itchat.auto_login(hotReload=True)  # 热启动你的微信
    #     # itchat.run()
    #     rooms = itchat.get_chatrooms(update=True)
    #     for i in range(len(rooms)):
    #         print(rooms[i])  # 查看你多有的群
    #     room = itchat.search_friends(name=r'郑小江')  # 这里输入你好友的名字或备注。
    #     print(room)
    #     userName = room[0]['UserName']
    #     path=LG.get_Image()
    #     print(path)
    #     f = path  # 图片地址
    #     try:
    #         itchat.send_image(f, toUserName=userName)
    #         # 如果是其他文件可以直接send_file
    #         print("success")
    #     except:
    #         print("fail")



    #
    # #下载验证码图片
    # def save_img(self):
    #     global imgPath
    #     if not os.path.exists('soures_img'):
    #         os.mkdir('soures_img')
    #     i=0
    #     while i<20:
    #         check_url=self.element('xpath','//*[@id="app"]/div/div[2]/form/div[3]/div/img').get_attribute("src")
    #         check_img=urllib.request.urlopen(check_url)
    #         data=check_img.read()
    #         imgPath='soures_img/%s.png'%(time.strftime("%Y%m%d%H%M%S"))
    #         print(imgPath)
    #         with open(imgPath,'wb') as f:
    #             f.write((data))
    #         time.sleep(3)
    #         check_click= self.element('xpath', '//*[@id="app"]/div/div[2]/form/div[3]/div/img').click()
    #     i += 1
    #     return imgPath
    #     # 下载验证码图片
    #
    # def save_img(self):
    #     global imgPath
    #     if not os.path.exists('soures_img'):
    #         os.mkdir('soures_img')
    #     i = 0
    #     while i < 50:
    #         check_url = self.element('xpath', '//*[@id="app"]/div/div[2]/form/div[3]/div/img').get_attribute("src")
    #         print(check_url)
    #         check_img = urllib.request.urlopen(check_url)
    #         # print(check_img)
    #         data = check_img.read()
    #         url = 'http://itm.huaguilife.cn/pre/auth/captcha.jpg'
    #         rs = requests.get(url).text
    #         rs = rs.split(',')
    #         key = rs[-1].split(':')[1].replace('}', '')
    #         str = key.replace("\"", "")
    #         print(str)
    #         # print(rs)
    #         # content=json.loads('{}'.format(rs))
    #         # print(content)
    #         # print(content["key"])
    #
    #         hours = time.strftime("%Y%m%d%H%M%S")
    #         imgPath = 'soures_img/%s(%s).png' % (hours, str)
    #         print(imgPath)
    #         with open(imgPath, 'wb') as f:
    #             f.write((data))
    #         time.sleep(3)
    #         check_click = self.element('xpath', '//*[@id="app"]/div/div[2]/form/div[3]/div/img').click()
    #         i += 1
    #     return imgPath



if __name__ == '__main__':
    driver=webdriver.Chrome()
    LG=Login(driver)
    LG.login('18886056204','GE8kQr.1','0')
    LG.write_dailywork(r"E:\工作日报\LI-华贵人寿项目组-PMC-项目周报（张元勇）-最新模板1.xlsx", '上周完成任务')
    weekdate=datetime.datetime.now().weekday() + 1
    print(weekdate)
    if weekdate==5:
        LG.write_weekwork(r"E:\工作日报\LI-华贵人寿项目组-PMC-项目周报（张元勇）-最新模板1.xlsx",'本周计划任务')
    else:
        print('%s不是周五，不需要填写周报报'%(datetime.date.today()))









